gpt4 book ai didi

c++ - CRTP 向下转换方法调用

转载 作者:行者123 更新时间:2023-11-30 01:45:06 30 4
gpt4 key购买 nike

任何人都可以向我解释为什么 base::blah(string str) 的签名必须是一个字符串而不是引用一个字符串。如果它是一个字符串,编译器会出现以下错误。是因为在模板实例化时编译器拒绝任何隐式转换吗?在我写这篇文章时,我想我可能已经回答了我自己的问题。不管怎样,代码在下面,下面又是错误。

#include <iostream>

using namespace std;

template <typename DERIVED>
class base {

public:

void blah(string& str){
cout << "blah string " << str << endl;
}

void blah(int i ){
cout << "blah int " << i << endl;
}

void foo( ) {
blah ((static_cast<DERIVED*> (this))->getIt());
}
};

class Derived1 : public base<Derived1> {
public:
typedef std::string type;
string getIt() {
cout << "getIt Derived1 called" << endl;
return std::string("string");
}
};

class Derived2: public base<Derived2> {
public:
typedef int type;
int getIt() {
cout << "getIt Derived2 called" << endl;
return 2;
}
};

int main(int argc, char** argv) {

Derived1 d1;
d1.foo();
Derived2 d2;
d2.foo();
return 0;
}

g++ main.cc
main.cc: In instantiation of ‘void base<DERIVED>::foo() [with DERIVED = Derived1]’:
main.cc:44:12: required from here
main.cc:19:54: error: no matching function for call to ‘base<Derived1>::blah(std::string)’
blah ((static_cast<DERIVED*> (this))->getIt());
^
main.cc:19:54: note: candidates are:
main.cc:10:10: note: void base<DERIVED>::blah(std::string&) [with DERIVED = Derived1; std::string = std::basic_string<char>]
void blah(string& str){
^
main.cc:10:10: note: no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘std::string& {aka std::basic_string<char>&}’
main.cc:14:10: note: void base<DERIVED>::blah(int) [with DERIVED = Derived1]
void blah(int i ){
^
main.cc:14:10: note: no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘int’

最佳答案

不,这是因为您不能将非常量引用绑定(bind)到临时对象。更改您的 blah 代码如下:

void blah(const std::string& str){
cout << "blah string " << str << endl;
}

错误会消失。

关于c++ - CRTP 向下转换方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35072555/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com