根据模板参数创建字符串 [英] Create strings depending on template arguments

查看:27
本文介绍了根据模板参数创建字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多这样的类/方法:

template<typename CharT, typename TraitsT = std::char_traits<CharT> >
struct Foo
{
   std::basic_string<CharT, TraitsT> getFoo(void) const
   {
     return "Foo"; // + this->member_var1 + this->member_var2...
   }
};

但是根据 CharT,我必须使用 "", L"", u"" 或 "U"(对于 char、wchar_t、u16char_t、u32char_t).

But depending on CharT, I have to use "", L"", u"" or "U" (for char, wchar_t, u16char_t, u32char_t).

必须使用什么语法来创建独立于此类模板参数的字符串?

What syntax must be used to create strings that are independed from such template arguments?

推荐答案

你真的需要不同的文字,或者你可以使用迭代器构造函数吗?

Do you really need the different literals, or can you use the iterator constructor?

const char *f = "Foo";
return std::basic_string<CharT, TraitsT>(f, f + 3);

如果您担心将来更改文字的难度,也许可以使用比3"更强大的东西.

Maybe with something a bit more robust than "3" in there, if you're worried about ease of changing the literal in future.

为了回应这不是很好的观点,怎么样:

In response to the point that this isn't very nice, what about:

template <typename CharT, typename TraitsT, size_t N>
basic_string<CharT, TraitsT> proper_string(const char (&src)[N]) {
    return basic_string<CharT, TraitsT>(src, src+N-1);
}

那么你有:

return proper_string<CharT, TraitsT>("Foo");

如果你真的需要不同的文字,那么到目前为止我唯一想到的就是为它创建特征,这真的很可怕:

If you really need the different literal, then the only thing I've thought of so far is to create traits for it, which is really horrible:

template<typename T> struct FooString {
};

template<> struct FooString<char> {
    static const char *value() { return "Foo"; }
};
template<> struct FooString<wchar_t> {
    static const wchar_t *value() { return L"Foo"; }
};
... etc ...

return FooString<CharT>::value();

这篇关于根据模板参数创建字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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