模板化类 - 在不支持的类上强制编译错误

Templated Class - Force compilation error on not supported class

本文关键字:编译 错误 不支持      更新时间:2023-10-16

我只在标准库中使用 C++03(跨平台(,我有一个模板化类,如果给出不支持的类,我想在编译时失败。到目前为止,我生成了一个运行时错误:

template <class Key, class Val>
class MyClass: public other_class<Key, Val>
{
public:
    template<class T1M, class T2M>
    struct ThisGetter
    {
        static T1M Get()
        { 
            throw(std::exception("Failed")); //Change this to compilation failure
        }
    };
    template<class T2M>
    struct ThisGetter<int, T2M>
    {
        static Key Get()
        {
            int temp = std::numeric_limits<int>::min();
            return temp;
        }
    };
};

如果可能的话,我希望有以下内容:

MyClass<int, int> works; // compilation successful
MyClass<string, int> fails; // compilation failed

可能吗?如果我理解正确,则无法删除第一个ThisGetter

谢谢

在 boost 出现一些问题后,我决定删除它。(由于某种原因在 CentOS7 上出现错误,但它在 CentOS6/win/Mac 上有效(我使用以下方法,声明:

template<bool> struct MyStaticAssert;
template<> struct MyStaticAssert<true> {};

在不需要的功能中:

foo()
{
    MyStaticAssert<false>()
}

开始喜欢模板:)