我打算有一个只专门处理 bool 或 char 类型而不使用 boost 的类。我的代码如下,我使用的是 VS2017 社区:
#include <type_traits>
template<typename T,
typename std::enable_if_t<
std::is_same<T, bool>::value || std::is_same<T, char>::value >::type >
class BoolAndCharData
{
public:
BoolAndCharData(const T& _data) {...}
void DoSomething() {...}
}; // end of class BoolAndCharData
int main()
{
char c;
BoolAndCharData<char> data(c); // error C2976: too few template parameter
....
} // end of main()
我尝试了另一种方式,就像这个网站上有人介绍的那样,编译器说它无法识别模板:
template<typename T>
class BoolAndCharData<T,
typename std::enable_if_t< std::is_same<T, bool>::value ||
std::is_same<T, char>::value >::type >
{
public:
BoolAndCharData(const T& _data) {...}
void DoSomething() {...}
}; // end of class BoolAndCharData
我浏览了这个网站和其他网站几个小时,发现虽然有很多关于限制模板类型的讨论,但大多数要么使用引导,要么特定于某个功能。我仍然不清楚如何编写具有选定数据类型的模板类。有没有好心人指点一下,让我免于盲目尝试?
最佳答案
您不需要使用 std::enable_if_t
来做到这一点。在这种情况下,static_assert
就足够了。
作为一个最小的工作示例:
#include <type_traits>
template<typename T>
class BoolAndCharData {
static_assert(std::is_same<T, bool>::value or std::is_same<T, char>::value, "!");
public:
BoolAndCharData(const T& _data) {}
void DoSomething() {}
};
int main() {
char c;
BoolAndCharData<char> d1(c);
// the following line won't compile
// BoolAndCharData<int> d2(0);
// ...
}
查看 Coliru .使用 static_assert
时的错误也比您通常从模板中得到的错误要好。
关于c++ - 仅使用 bool 和 char 定义模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44609264/