c++ - 仅使用 bool 和 char 定义模板类

标签 c++ templates c++14 sfinae restrict

我打算有一个只专门处理 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/

相关文章:

c++ - 在 C++ 中使用数组

c++ - 按共享指针 vector 中的值删除

c++ - 为什么我的函数模板特化被 VS2017 拒绝而不是被 VS2015 拒绝?

java - 有没有办法实现一个通用类来显示对象字段?

.net - 片段和模板有什么区别?

c++ - 使用嵌套模板进行模板化

c++ - 引发异常:写访问冲突。 temp为nullptr

c++ - Windows下C++项目中使用cpp-netlib

c++ - 在隐式参数转换中使用演绎指南

c++ - VS2012 预编译头文件 : how does my . h 文件知道包含在 stdafx.h 中吗?