在编译时检查模板参数是否是一种字符串

Check at compile time that a template parameter is a kind of string

本文关键字:字符串 一种 是否是 参数 编译 检查      更新时间:2023-10-16

假设我有一个函数:

template <typename T>
void foo(const T& arg) {
   ASSERT(is_valid<T>::value == true);
   // ...
}

is_valid检查T是字符串还是整数。我可以轻松地制作可以为我做到这一点的结构:

template <typename T>
struct is_integer { static const bool value = false; };
template <>
struct is_integer<int> { static const bool value = true; };
template <typename T>
struct is_string { static const bool value = false; };
template <>
struct is_string<std::string> { static const bool value = true; };

然后使用这两种结构来检查参数:

template <typename T>
struct is_valid { 
    static const bool value = is_string<T>::value || is_integer<T>::value; 
};

但是,我似乎错过了一些字符串类型。是否有面向所有字符串类型的C++类型?是否已经有一个结构或功能可以为我做到这一点?

我得到了:

  • std::string
  • char*
  • char[]

在我的is_string结构中,但这似乎还不够。我没有通过const&(参考文献),因为它不是这样测试的:从const T&论点来看,只测试了T

如果以下字符串定义适合您:

T是一个字符串,当且仅当它可用于构造std::string

然后,您可以使用以下命令定义is_string<T>

template <typename T>
using is_string = std::is_constructible<std::string, T>;

is_constructible可以用 C++98 :)


关于大肠杆菌的演示:

#include <string>
#include <type_traits>
template <typename T>
using is_string = std::is_constructible<std::string, T>;
#include <iostream>
int main()
{
    std::cout << std::boolalpha
        << is_string<const char*>::value << "n"
        << is_string<volatile char*>::value << "n"
        << is_string<std::string>::value << "n"
        ;
}

输出:



相关文章: