带有 `const char*` 的模板别名

问题描述 投票:0回答:1

我想别名/专门化一个采用

const char*
作为模板参数的模板:

#include <iostream>

template<float v, const char* unit>
struct Displayer {
    void display() const {
        std::cout << v << ' ' << unit << '\n';
    }
};

template<float v>
using MetricDisplayer = Displayer<v, "m">;

int main()
{
    MetricDisplayer<2.5> height;
    height.display();
    return 0;
}

但是这会产生错误

<source>:11:41: error: '"m"' is not a valid template argument for type 'const char*' because string literals can never be used in this context
。嗯...什么上下文,别名?那我可以做专业吗?

template<float v>
struct MetricDisplayer : public Displayer<v, "m">;

不...同样的错误消息:

<source>:11:49: error: '"m"' is not a valid template argument for type 'const char*' because string literals can never be used in this context

所以这里我的问题:我怎样才能有一个相当优雅的符号来用特定的字符串文字实例化

Displayer

编辑:我没有注意到,但是

#include <iostream>

template<float v, const char* unit>
struct Displayer {
    void display() const {
        std::cout << v << ' ' << unit << '\n';
    }
};

int main()
{
    Displayer<2.5f, "m"> height;
    height.display();
    return 0;
}

根本不起作用! 所以我的新问题是...如何在不变的字符串值上正确创建模板?

c++ templates c++20 type-alias
1个回答
0
投票

我会这样做:

#包括

// helper to create a string you can use as template parameter
template <std::size_t N>
struct template_string
{
    constexpr template_string(const char (&string)[N]) 
    {
        for(std::size_t n{ 0ul }; n < N; ++n)
            m_string[n] = string[n];
    }

    constexpr std::string_view sv() const noexcept
    {
        return std::string_view{m_string,N};
    }

   
    char m_string[N]{};
};

template<typename template_string unit>
struct Displayer 
{
    static void display(float value) 
    {
        std::cout << value << ' ' << unit.sv() << '\n';
    }
};

int main()
{
    Displayer<"Volt">::display(1.0);
}
© www.soinside.com 2019 - 2024. All rights reserved.