【问题标题】:Check at compile time that a template parameter is a kind of string在编译时检查模板参数是一种字符串
【发布时间】:2017-10-06 22:22:44
【问题描述】:

假设我有一个函数:

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&amp;(参考),因为它没有经过测试:从 const T&amp; 参数,只有 T 被测试。

【问题讨论】:

  • 是什么让您认为您缺少某些类型?您是否传递了应该被检测为字符串但没有传递的东西?你通过了什么?
  • 你认为什么是字符串? /*const*/char[N], std::wstring, QString, vector&lt;char&gt;, ...
  • en.cppreference.com/w/cpp/string/basic_string 这可能有帮助也可能没有帮助
  • 考虑使用#include 。 std::remove_cv、std::is_same、std::is_constructible
  • 您首先必须定义一个字符串的定义(Jarod 的注释)。一个建议,T 是一个字符串,如果 std::string(T const&amp;) 存在;即is_constructible&lt;std::string, T&gt;::value == true(安德烈的评论)。

标签: c++ typetraits c++98


【解决方案1】:

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

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

然后,你可以定义is_string&lt;T&gt;

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

还有is_constructible is definable in C++98 :)


Demo on coliru:

#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"
        ;
}

输出:

是的

真的

【讨论】:

  • 我认为你不需要第一个结构模板
  • @Caleth 实际上
  • 它适合我是的。我喜欢这个主意。我需要在 C++98 中找到一种方法来做到这一点
  • @baptiste 你可以在 C++98 中定义std::is_constructible
  • 我看到了同样的问题;)
猜你喜欢
  • 1970-01-01
  • 2021-07-02
  • 1970-01-01
  • 2012-03-26
  • 2015-09-11
  • 1970-01-01
  • 2021-11-13
  • 2021-07-08
  • 2015-08-24
相关资源
最近更新 更多