【发布时间】:2020-03-20 04:27:55
【问题描述】:
我有一个定义如下的类模板
template<typename T>
class A
{
T t_;
// void f();
};
我的问题是,只有在类型 T 是整数且没有编译错误的情况下,如何添加 f() 方法。
int main()
{
A<int> a; // OK
A<string> b; // OK
}
例子:
#include <type_traits>
#include <new>
#include <iostream>
#include <string>
template <typename T>
struct Foo
{
T t;
template <typename..., typename U = T>
std::enable_if_t<std::is_same_v<T, int>> say_hello() { std::cout << "Hello"; }
};
int main()
{
Foo<int>();
Foo<double>();
}
Error C2938 'std::enable_if_t<false,void>' : Failed to specialize alias template
谢谢。
【问题讨论】:
-
不,如果我实例化一个非整数类型的类,我会得到一个编译错误
-
不,我想为每种类型都正确编译
-
@Roger Edit 包含一个描述错误的minimal reproducible example 的问题。我没有收到任何编译错误:wandbox.org/permlink/M3k6VVQlmINT1CNU
-
应该是
std::is_same_v<U, int>,而不是std::is_same_v<T, int>。