c++ 创建方法, Package 每个模板类方法用于日志记录目的[已关闭]

uinbv5nw  于 2023-04-13  发布在  其他
关注(0)|答案(1)|浏览(74)

**已关闭。**此问题需要debugging details。当前不接受答案。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
3天前关闭。
Improve this question
我有错误,当我试图创建方法, Package 所有模板类方法的日志记录的目的。
我固定了我的类和方法的声明log_call是我尝试的。如何解决这个问题,或者可能有其他解决方案可以工作。我想在任何其他方法调用时调用log()函数,而不是在每个方法中硬编码它。

template <class DataUnit>
class ModelManager {
public:
    ModelManager(std::string source, std::string path);
    std::vector<DataUnit> copy();
    std::vector<DataUnit> copy(std::map<std::string, std::string> by_what);

    template <typename R, typename... TArgs>        
    R log_call(R (ModelManager<DataUnit>::*f)(TArgs...), const TArgs... args) {
        this->log();
        return (this->*f)(args...);
    }

private:
    void log() {
        std::cout << "Called!" << "\n";
    };
};

然后我试着用下面的方法,并得到一个错误.

ModelManager<Client> manager("txt", "clients.txt");
manager.log_call(&ModelManager<Client>::copy);

实际误差

models/base_model_manager.h:47:11: note:   template argument deduction/substitution failed:
main.cpp:22:34: note:   couldn't deduce template parameter 'R'
   22 |     std::cout << manager.log_call(&ModelManager<Client>::copy) << "\n";
      |                  ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
yzxexxkh

yzxexxkh1#

实际的错误是歧义:unresolved overloaded function type,但是您只显示了错误消息四个部分中的最后一个部分。

<source>:68:21: error: no matching function for call to 'ModelManager<Client>::log_call(<unresolved overloaded function type>)'
   68 |     manager.log_call(&ModelManager<Client>::copy);
      |     ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:40:11: note: candidate: 'template<class R, class ... TArgs> R ModelManager<DataUnit>::log_call(R (ModelManager<DataUnit>::*)(TArgs ...), const TArgs ...) [with R = R; TArgs = {TArgs ...}; DataUnit = Client]'
   40 |         R log_call(R (ModelManager<DataUnit>::*f)(TArgs...), const TArgs... args) {
      |           ^~~~~~~~
<source>:40:11: note:   template argument deduction/substitution failed:
<source>:68:21: note:   couldn't deduce template parameter 'R'
   68 |     manager.log_call(&ModelManager<Client>::copy);
      |     ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~

你有两个重载函数ModelManager<T>::copy,你要把&ModelManager<Client>::copy中的哪一个传递给log_call
正确的代码:

manager.log_call(static_cast<std::vector<Client>(ModelManager<Client>::*)()>(
  &ModelManager<Client>::copy));

相关问题