c++ - 我可以模板化用户定义的文字吗?

标签 c++ c++11 templates user-defined-literals

假设我有一些类(class):

template <typename T>
class Foo {
  const T* x_;
public:
  Foo(const T* str) : x_{str} {}
};

我提供了一些创建 Foo 对象的用户定义文字:

Foo<char> operator"" _foo(const char* str, std::size_t) {
  return Foo<char>{str};
}

Foo<wchar_t> operator"" _foo(const wchar_t* str, std::size_t) {
  return Foo<wchar_t>{str};
}

// etc. for char16_t and char32_t.

我的问题是:为什么我不能将这些模板化而不必重写代码?

template <typename T>
Foo<T> operator"" _foo(const T* str, std::size_t) {
  return Foo<T>{str};
}

gcc 5.4.0(Ubuntu 5.4.0-6ubuntu1~16.04.4)和7.0.0(自己编译)报告:

error: ‘Foo<T> operator""_foo(const T*, std::size_t)’ has invalid argument list
Foo<T> operator"" _foo(const T* str, std::size_t) {
                                                ^

错误信息似乎很清楚,但我没有看到原则上不允许我这样做的原因;那么,我这样做是不对的,还是真的不允许这样做?

最佳答案

考虑 this :

If the literal operator is a template, it must have an empty parameter list and can have only one template parameter, which must be a non-type template parameter pack with element type char

换句话说,文字运算符模板的声明应该是:

template <char...> double operator "" _x();

那不是你的情况。


我不是语言律师,但我想与您的案件相关的标准部分是 [over.literal] (链接到工作草案)。

摘自 [over.literal]/2如下:

A function template declared with a literal-operator-id is a literal operator template.

下方[over.literal]/5引用:

The declaration of a literal operator template shall have an empty parameter-declaration-clause and its template-parameter-list shall have a single template-parameter that is a non-type template parameter pack ([temp.variadic]) with element type char.

在我看来,与问题中的声明类似的声明被标准明确禁止。
更一般地说,声明文字运算符的函数模板必须严格遵守给定的模式。


am I doing this incorrectly, or is this genuinely not allowed?

我会说这是确实不允许

无论如何,如果您有不想在每个运算符中重复的复杂逻辑,您仍然可以使用模板函数:

template<typename T>
Foo<T> create(const T *str) {
    // your logic...
    return Foo<T>{str};
}

Foo<char> operator"" _foo(const char *str, std::size_t) {
    return create(str);
}

Foo<wchar_t> operator"" _foo(const wchar_t *str, std::size_t) {
    return create(str);
}

这是一个额外的间接层的问题,仅此而已。
显然,如果你所有的操作符都是一行体函数,那是不值得的。

关于c++ - 我可以模板化用户定义的文字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41506343/

相关文章:

c++ - 静态断言添加操作是否可用

c++ - 在模板链表中没有调用查找的匹配函数

c++ - 如何取消C++/WRL中的异步回调函数?

C++0x lambda + boost::function 问题

c++ - 没有 "predicate"的对 vector 上的 max_element

c++ - 尝试理解模板和名称查找

c++ - 我怎样才能从模板派生两次,并让子类交互?

c++ - 如何在 Windows 中创建线程安全的单例模式?

c++ - 我们是否应该在大型 std::vector 中存储指向类实例的智能指针以获得更好的性能?

c++ - 当有两个具有不同签名的函数时,为什么 SFINAE 会导致失败?