首页 > 解决方案 > 与模板实例化相关的编译错误

问题描述

以下测试程序在较大程序的上下文中重现编译错误:

#include <algorithm>
#include <iostream>
#include <vector>
using std::for_each;
using std::vector;
using std::cout;
using std::endl;

template<typename T, typename C = vector<T>>
class display_container{
    public:
        display_container(const C& cr):this->cr(cr){this->();}
        ~display_container(){}
    private:
        constexpr void operator () (void){if(cr.empty()){cout << "NULL" << " ";} else{for_each(cr.begin(), cr.end(), [](const T& crt){cout << crt << " ";});}}
        const C& cr;
};

int main (void){

    int n = 5;
    vector<int> vec(n, 0);
    display_container d(vec);
    cout << endl;

    return 0;
}

以下是编译器错误的日志:

g++ -ggdb -std=c++17 -Wall -Werror=pedantic -Wextra  -c code.cpp
code.cpp: In constructor ‘display_container<T, C>::display_container(const C&)’:
code.cpp:12:40: error: expected identifier before ‘this’
         display_container(const C& cr):this->cr(cr){this->();}
                                        ^~~~
code.cpp:12:40: error: expected ‘{’ before ‘this’
code.cpp: In function ‘int main()’:
code.cpp:23:28: error: class template argument deduction failed:
     display_container d(vec);
                            ^
code.cpp:23:28: error: no matching function for call to ‘display_container(std::vector<int>&)’
code.cpp:12:9: note: candidate: template<class T, class C> display_container(const C&)-> display_container<T, C>
         display_container(const C& cr):this->cr(cr){this->();}
         ^~~~~~~~~~~~~~~~~
code.cpp:12:9: note:   template argument deduction/substitution failed:
code.cpp:23:28: note:   couldn't deduce template parameter ‘T’
     display_container d(vec);
                            ^
code.cpp:10:7: note: candidate: template<class T, class C> display_container(display_container<T, C>)-> display_container<T, C>
 class display_container{
       ^~~~~~~~~~~~~~~~~
code.cpp:10:7: note:   template argument deduction/substitution failed:
code.cpp:23:28: note:   ‘std::vector<int>’ is not derived from ‘display_container<T, C>’
     display_container d(vec);
                            ^
make: *** [makefile:20: code.o] Error 1

我认为剩余的错误是从与display_container模板类的内联构造函数定义相关的第一个错误开始的。

关于与内联构造函数定义相关的代码有什么问题的任何建议?

TIA

标签: c++templatescompiler-errors

解决方案


编译器还不能获取向量的模板类型:

#include <algorithm>
#include <iostream>
#include <vector>

using std::for_each;
using std::vector;
using std::cout;
using std::endl;

template<typename T, typename C = vector<T>>
class display_container{
    public:
        display_container(const C& cr): cr(cr) { (*this)(); }
        ~display_container(){}
    private:
        constexpr void operator () (void){if(cr.empty()){cout << "NULL" << " ";} else{for_each(cr.begin(), cr.end(), [](const T& crt){cout << crt << " ";});}}
        const C& cr;
};

int main (void){

    int n = 5;
    vector<int> vec(n, 0);
    display_container<int> d(vec);
    cout << endl;

    return 0;
}

推荐阅读