为模板类中的无效数据类型生成编译时错误? [英] Generating compile time errors for invalid data types in a template class?

查看:143
本文介绍了为模板类中的无效数据类型生成编译时错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C ++来创建一个字符串类。我想类只接受数据类型char和wchar_t,我想让编译器捕获任何无效的数据类型在编译时使用#error。我不喜欢使用assert()。如何做到这一点?

I am using C++ to create a string class. I want the class to only accept the data types char and wchar_t and I want the compiler to catch any invalid data types during compile time using #error. I do not like using assert( ). How can I do this?

推荐答案

可以使用静态断言。 Boost 提供一个

You can use a static assert. Boost provides one.

也许像:

#include <boost/type_traits.hpp>
#include <boost/static_assert.hpp>

template <typename T>
class my_string
{
public:
    // ...
private:
    BOOST_STATIC_ASSERT((boost::is_same<T, char>::value ||
                          boost::is_same<T, wchar_t>::value));
};

int main(void)
{
    my_string<char> chstr;
    my_string<wchar_t> wstr;

    // fails
    my_string<int> istr;
}



如果您不能使用Boost,您可以轻松地重新创建static-assert和 is_same

// static assert failure
template <bool Predicate>
struct STATIC_ASSERT_FAILURE;

template <>
struct STATIC_ASSERT_FAILURE<true> {}; // only true is defined

// static assert test
template <unsigned TestResult>
struct static_assert {};

// static assert macro
#define STATIC_ASSERT(x) typedef static_assert< \
                          sizeof(STATIC_ASSERT_FAILURE<(x)>)> \
                          _static_assert_test_

// value is true if T and U are the same type
template <typename T, typename U>
struct is_same
{
    static const bool value = false;
};

template <typename T>
struct is_same<T, T>
{
    static const bool value = true;
};

template <typename T>
class my_string
{
public:
    // ...
private:
    STATIC_ASSERT((is_same<T, char>::value || is_same<T, wchar_t>::value));
};

int main(void)
{
    my_string<char> chstr;
    my_string<wchar_t> wstr;

    // fails
    my_string<int> istr;
}

注意,如果在同一个命名空间中使用一个静态断言两次,会得到名字冲突。您必须使用更复杂的版本,使用 __ COUNTER __ 等宏来生成唯一的名称。

Note, if you use a static assert in the same namespace twice, you'll get a name collision. You' have to use a more sophisticated version that uses a macro such as __COUNTER__ to generate unique names.

以上工作在GCC 4.4和Visual Studio 2008。

The above works in both GCC 4.4 and Visual Studio 2008.

这篇关于为模板类中的无效数据类型生成编译时错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆