【问题标题】:invalid template argument for 'N', expected compile-time constant expression“N”的模板参数无效,预期的编译时常量表达式
【发布时间】:2012-07-10 11:19:50
【问题描述】:

我正在创建一个高精度浮点库(用于教育目的),构造函数如下所示。

这个想法是有一个通用构造函数(第一个),然后是 std::string 和 std::bitset 的 2 个专用构造函数。

问题是我不断收到:“错误 C2975:'Float':'N' 的模板参数无效,预期的编译时常量表达式”对于两个专门的构造函数。

谁能告诉我如何纠正这个问题?

提前致谢!

template<typename T>
Float(T n) {
    type_wrapper<T> data;
    data.in = n;
    bits = std::bitset<N>(data.out);
    _overflow = false;
}

template<>
Float< const std::bitset<N> >(const std::bitset<N> bits) {
    this->bits = bits;
    _overflow = false;
}

template<>
Float< const std::string& >(const std::string& s) {
    int n = std::min(N, s.length());
    for(int i = 0; i < n; i++) {
        bits[n-i-1] = (s.at(i) == '1' ? 1 : 0);
    }
    _overflow = false;
}

编辑:我可能应该补充一点,我实际上是在构造一个具有恒定大小的 Float 对象,如下所示:

int main(int argc, char* argv[])
{
    Float<64> number("01011001100010001110010101100111");   //1502143847
    std::cout << number << std::endl;

    std::cin.get();
    return 0;
}

模板化参数“N”也来自类定义,如下所示:

template<size_t N>
class Float
{
private:
    ...
public:
    ...
};

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    不要专门化你的构造函数,使用重载。

    #include <cstdint>
    #include <bitset>
    #include <string>
    #include <iostream>
    template<std::size_t N>
    class Float
    {
    private:
    
    public:
      template<typename T>
      Float(const T& n) {
      }
    
      Float(const std::bitset<N>& bits) {
      }
    
      Float(const std::string& s) {
      }
    };
    
    int main()
    {
        Float<64> number("01011001100010001110010101100111");   //1502143847
    
        std::cin.get();
        return 0;
    }
    

    最初的错误可能是因为您在定义构造时没有完全限定它们。这应该是:

    template<std::size_t N>
    template<>
    Float<N>::Float<const std::string&>(const std::string&) {}
    

    【讨论】:

    • 最初我确实重载了构造函数,但问题是每次都调用泛型构造函数而不是更具体的构造函数。构造函数也是完全限定的,因为“N”模板参数是在类定义的顶部定义的。
    • @MathiasVorreiterPedersen 这不可能。你能显示导致这种情况的代码吗?尽管在 string 重载和使用字符串文字调用的情况下,这是预期的行为。生成的构造函数(来自模板实例化)Float(char*) 的排名高于需要转换为 string 的构造函数。一般来说,这不应该是真的。
    • 你是对的。当我从字符串文字显式构造一个 std::string 对象时,应用了正确的构造函数。所以我想如果我只是为 char* 参数创建另一个构造函数,一切都会很好。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多