C++ template specialization without default function

后端 未结 5 1677
轻奢々
轻奢々 2021-02-01 02:49

I have the following code that compiles and works well:

template
T GetGlobal(const char *name);

template<>
int GetGlobal(cons         


        
5条回答
  •  耶瑟儿~
    2021-02-01 03:29

    To get a compile-time error implement it as:

    template
    T GetGlobal(const char *name) { T::unimplemented_function; }
    // `unimplemented_function` identifier should be undefined
    

    If you use Boost you could make it more elegant:

    template
    T GetGlobal(const char *name) { BOOST_STATIC_ASSERT(sizeof(T) == 0); }
    

    C++ Standard guarantees that there is no such type which has sizeof equal to 0, so you'll get a compile-time error.

    As sbi suggested in his comments the last could be reduced to:

    template
    T GetGlobal(const char *name) { char X[!sizeof(T)]; }
    

    I prefer the first solution, because it gives more clear error message (at least in Visual C++) than the others.

提交回复
热议问题