V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
jmc891205
V2EX  ›  C

请问为什么编译器推断不出这里的 Nontype Template Parameter(非类型模板参数?)呢?

  •  
  •   jmc891205 · 2016-01-12 00:11:53 +08:00 · 720 次点击
    这是一个创建于 3031 天前的主题,其中的信息可能已经有所发展或是发生改变。

    用的编译器是 clang-700.1.81

    #include <iostream>
    using namespace std;
    
    template <unsigned N, unsigned M>
    void compare(const char p1[N], const char p2[M]) {
      cout << N << ", " << M << endl;
    }
    int main() {
      compare("hi", "hello");
      return 0;
    }
    

    错误信息是:

    test.cpp:9:3: error: no matching function for call to 'compare'
      compare("hi", "hello");
      ^~~~~~~
    test.cpp:5:6: note: candidate template ignored: couldn't infer template argument
          'N'
    void compare(char p1[N], char p2[M]) {
         ^
    1 error generated.
    

    请问这里为什么编译器推断不出 N 为 3, M 为 6 呢?
    但是如果参数是用引用,那就可以了。

    #include <iostream>
    using namespace std;
    
    template <unsigned N, unsigned M>
    void compare(const char (&p1)[N], const char (&p2)[M]) {
      cout << N << ", " << M << endl;
    }
    int main() {
      compare("hi", "hello");
      return 0;
    }
    
    3 条回复    2016-01-12 11:47:59 +08:00
    yangff
        1
    yangff  
       2016-01-12 00:28:01 +08:00
    大概是类型?

    void fuck(const char p1[3]) {
    cout << typeid(p1).name();
    }
    msg7086
        2
    msg7086  
       2016-01-12 00:30:47 +08:00
    帮你用 gcc 跑了一下,得出以下错误信息:

    test.cpp:5:6: note: candidate: template<unsigned int N, unsigned int M> void compare(const char*, const char*)
    void compare(const char p1[N], const char p2[M]) {
    ^

    所以很明显不是引用的时候变成了 const char * 了。
    jmc891205
        3
    jmc891205  
    OP
       2016-01-12 11:47:59 +08:00
    @msg7086 谢谢!我明白了~
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2479 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 15:05 · PVG 23:05 · LAX 08:05 · JFK 11:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.