0

I define a function template alias:

template <typename T>
using Cb = typename std::add_pointer<void(bool, T)>::type;

but got this error :

error: cannot convert 'Log::operator()(Read&) [with T = int]::' to 'Cb' {aka 'void (*)(bool, int)'} in assignment

template <typename T>
class Log : public Sink<T> {
public:
    void
    operator()(Read<T> &read) {
        if (!more_) {
            // error !!!
            more_ = std::function<Cb<T>>([&](bool done, T val) {
                if (!done) {
                    cout << val << endl;
                    this->operator()(read);
                }
            });
        }
        read(false, more_);
    }

private:
    Cb<T> more_ = nullptr;
};

main function:

int main() {

    Log<int> logInt;

    return 0;
}

who to resolve this syntax error?

code example

langyu
  • 68
  • 1
  • 7
  • 2
    Lambda with captures cannot be casted to pointer to function. It could only work with stateless lambdas. Put the link with real code, now it doesn't match what you posted in question. – rafix07 Jan 29 '20 at 06:22
  • but, how to correct it, can you help me? this is the real code example: http://coliru.stacked-crooked.com/a/d8d76f665ea07898 – langyu Jan 29 '20 at 06:24
  • 4
    Why not just define `Cb` as: `template using Cb = std::function;` ? – rafix07 Jan 29 '20 at 06:27
  • Fully agree with rafix07. Here is a [live example](http://coliru.stacked-crooked.com/a/544045333da0315c) – StefanKssmr Jan 29 '20 at 06:49
  • Thanks rafix07 and StefanKssmr, the live example is right – langyu Jan 29 '20 at 07:07
  • another question, how to make this line `this->operator()(read);` tail recursion optimization enabled @StefanKssmr in the [live example](http://coliru.stacked-crooked.com/a/77d1df531d3f357f) – langyu Jan 29 '20 at 07:44
  • @langyu maybe [this answer](https://stackoverflow.com/a/2693702/8359552) helps to restructure your `void Log::operator()(Read &read)`. To enable tail recursion optimisation `this->operator()(read)` should be the last statement in your function. – StefanKssmr Jan 29 '20 at 08:12

1 Answers1

0

Issue is that

std::function<Cb<T>> resolve to std::function<void (*)(bool, int)> whereas you want

std::function<void (bool, int)>.

So you might change your alias to

template <typename T>
using Cb = void(bool, T);
Jarod42
  • 203,559
  • 14
  • 181
  • 302